#[macro_use] extern crate tera;
extern crate rusty_copybook;

use std::fs::File;
use std::io::{Read};

use clap::{App, Arg};

use rusty_copybook::{Result, Record, TokenStream, Parser, tokenize, render_module};

fn main() -> Result<()>{
    let matches = App::new("COBOL copybooks to Rust transpiler")
        .arg(Arg::with_name("copybook")
             .short("c")
             .long("copybook") 
             .help("Path to COBOL copybook file") 
             .required(true)
             .takes_value(true))
        .arg(Arg::with_name("output")
             .short("o")
             .long("output")
             .help("Name of the Rust output file, defaults to $copybookname.rs")
             .takes_value(true))
        .arg(Arg::with_name("drop-field-prefix")
             .help("Field name prefix to be dropped")
             .long("drop-field-prefix")
             .takes_value(true))
        .get_matches();
    let cpy_name = matches.value_of("copybook").unwrap();
    let rs_name = matches.value_of("output");
    let drop_field_prefix = matches.value_of("drop-field-prefix");
    let mut cpy_file = File::open(cpy_name)
        .expect("Input copybook not found");
    let mut buf = String::new();
    cpy_file.read_to_string(&mut buf)?;
    let tokens = tokenize(&buf, drop_field_prefix);
    let mut stream = TokenStream::new(tokens);
    let root_record = Record::parse(&mut stream, 0)?;
    let tera = compile_templates!("./templates/*.tera");
    render_module(root_record, &cpy_name, rs_name, &tera)?;
    Ok(())
}
